package com.houdoudou.supplier.common;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dwin.navy.serialportapi.SerailPortOpt;
import com.houdoudou.supplier.bean.Order;
import com.houdoudou.supplier.bean.OrderProduct;

public class ZebraPrinter {

	/*--------文本参数------*/ 
	  // GK88t 200dpi, 1mm含8dot， 目前标签宽60mm,480dot 高40mm,320dot,标签间隙2mm,16dot
	    final String ENTER="\r\n";

	    final int FONT_CHS=8; // (32 x 32 dots)
	    final int GAP_FONT_CHS=35; // (14 x 24 dots)
	    
	    final int GAP_LABEL=16; // 
	    final int HEIGHT_LABEL=320; // 
	    final int WIDTH_LABEL=480; // )
	    
	    final int ROTATE00=0;
	    final int MULITYX=1;
	    final int MULITYY=1;
	    final String BG_BLACK="R";
	    final String BG_WHITE="N";
	    
		/*--------线参数------*/
	    final int LINE_WIDTH=1;  //分割线宽
	    	    
		/*--------条码参数------*/

		final int BAR_TYPE=9; //  93码
		final int NARROW_BAR_WIDTH=2; //  93码取值1-10
		final int WIDE_BAR_WIDTH=4; //  Acceptable values are 2-30.
		final int BAR_HEIGHT=100;  // 条码高度
		
		final int AVERAGE_CHAR_WIDTH=16;  // 平均一个数字
		
		final String BAR_NUMBER_SHOW="B"; //
		final String BAR_NUMBER_HIDE="N"; //
		
		/*--------页面参数------*/
		final int PADDING_VERTICAL=3;  // 顶部空隙
		final int PADDING_HORIZON=3;  // 左边空隙
		
		
	public SerailPortOpt  serialPortOpt;
	public InputStream mInputStream;
	
	
	public ZebraPrinter() {
		super();
		// TODO Auto-generated constructor stub
		
		initSerialPort();
	}
 /*
  
  这是一个订单数据

{"moneyCompany":-1,"supplierName":"商家测试1

号","timeFlag":1,"dateTimeRDL":"20150910120000","dateAA":"20150903","ownerTelnum":"18620302330","dateTimeAI":"","machineID"

:3,"courierRKTelnum":"","productNum":2,"moneyCu":31,"rateOw":0.1,"dateTimeRF":"","isRefund":2,"machineAddress":"广安厚豆自

提柜测试1号机","rateSu":0.1,"dateTimeRK":"","dateTimeRL":"201509031000","machineName":"厚豆自提柜测试1号

机","boxFeeCu":1,"moneyOwner":-1,"state":10,"id":21,"boxFeeSu":0.5,"courierAITelnum":"","moneySupplier":-1,

"refund":

{"dateTimeS":"","result":3,"dateTimeCP":"20150909201539","orderID":21,"reason":"","state":10,"dateTimeOL":"20150910201539",

"type":1,"dateTimeO":"","dateTimeCL":"","dateTimeC":"","dateTimeCC":"20150909201643","owner":"","money":2,"dateTimeSL":"201

51010000000","supplier":"18620302330"},

"boxVolume":100,

"products":

[{"branchID":0,"orderID":21,"dir":"http://192.168.1.115:8080/houdoudou/userImages/18620302330/13581617523/28/0.jpg","branch

Num":1,"branchPrice":20,"branchVolume":20,"branchName":"默认","productID":30,"productName":"蒸烧白","productType":2},

{"branchID":0,"orderID":21,"dir":"http://192.168.1.115:8080/houdoudou/userImages/18620302330/13581617523/28/0.jpg","branchN

um":1,"branchPrice":10,"branchVolume":50,"branchName":"大份","productID":31,"productName":"到底是","productType":2}],


"isMoneyDealed":1,"note":"","customerTelnum":"18620302330","dateTimePL":"20150902210504","isMoneyPaid":2,"isBoxUsed":1,"box

Num":1,"dateTimeAA":"20150903080000","moneyFreight":1,"supplierTelnum":"12345678901","dateTimeAB":"","dateTimeAE":"20150903

0700","courierABTelnum":"","boxesIn":"","volume":70,"secret":"910806","dateTimePA":"20150908214502","dateTimeTK":"","servic

eTelnum":"12345678901","dateTimeTL":"201509030900","moneyProduct":30},



   */
	private String spellOneProduct(String product,String branch,String number){
		String DASH="-";
		String online="";
		int widthOfChar=product.length()*2+branch.length()*2+number.length(); //char长度
		int dash_num=((WIDTH_LABEL-20)/18-widthOfChar)/2; //中间间隔
		if(dash_num<0) dash_num=0; //不能为负数
		online+=product;	
		for(int i=0;i<dash_num;i++){
			online+=DASH;
		}
		online+=branch;
		for(int i=0;i<dash_num;i++){
			online+=DASH;
		}
		online+=number;	
		return online;
	}
	
	private String getOneRowWord(String word,int startX,int startY,int textSize){
	   
		String src="";
		
		src+="A";
		src+=startX+",";
		src+=startY+",";
		src+=ROTATE00+",";
	    src+=FONT_CHS+","; // 尝试中文	
		src+=MULITYX+",";
		src+=MULITYY+",";
		src+=BG_WHITE+",";
		src+="\""+word+"\"";
		
		return src;
	}
	private String getOneBar(String barData,int startY){
	
		int startX=(WIDTH_LABEL-AVERAGE_CHAR_WIDTH*(barData.length()+6))/2;
		//  B10,10,0,3,3,7,200,B,"998152-001"
		String src="";		
		src+="B"+startX+",";
		src+=startY+",";
		src+=ROTATE00+",";
		src+=BAR_TYPE+",";
		src+=NARROW_BAR_WIDTH+",";
		src+=WIDE_BAR_WIDTH+",";
		src+=BAR_HEIGHT+",";
		src+=BAR_NUMBER_HIDE+",";
		src+="\""+barData+"\"";
		// 3,3,7,200,B,"+"\""+"998152-001"+"\"";
		
		return src;
	}
	
	private String getOnePrintCode(){
		int positionYNow=PADDING_VERTICAL;
		String src="";
		src+="N";	
		src+=ENTER;		
	    
	    //条码
	    positionYNow=jumpGapOfLabel(positionYNow,BAR_HEIGHT);
		src+=getOneBar("12345678901234567890", positionYNow);
		src+=ENTER;	
		positionYNow+=BAR_HEIGHT;    //显示二维码数字的文本高度。
	   
		positionYNow+=5; //留点空隙	
		
		//订单号
				positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
				src+=getOneRowWord("单号:9010", PADDING_HORIZON,positionYNow,  FONT_CHS);			
				src+=ENTER;	
			    positionYNow+= GAP_FONT_CHS;
			    
		//时间
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("时间:2015-10-09 12：40：00", PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
		positionYNow+= GAP_FONT_CHS;	
		//时间
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("地址:广安厚豆自提柜1号机", PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
		positionYNow+= GAP_FONT_CHS;      
		//客户
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("客户:18620302330", PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
	    positionYNow+= GAP_FONT_CHS+5;
		 
		for(int i=0; i<4;i++){
			String word=spellOneProduct("青椒肉丝","大份","2");
		//一个菜品	
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord(word, PADDING_HORIZON,positionYNow, FONT_CHS);	
		src+=ENTER;
	    positionYNow+= GAP_FONT_CHS;
	    
		//分割线		
		// src+="LS10,"+ positionYNow+","+LINE_WIDTH+",470,"+ positionYNow;
		// src+=ENTER;	
		}
		
		
		//商家	
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("商家:18620302330", PADDING_HORIZON,positionYNow,  FONT_CHS);	
		src+=ENTER;		
		
		src+="P1";
		src+=ENTER;		
		return src;
	}
	
	
	private String getOneOrderCode(JSONObject orderJO){
		int positionYNow=PADDING_VERTICAL;
		String src="";
		src+="N";	
		src+=ENTER;	
		
		//订单号
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("单号:"+orderJO.getLong(Order.ID), PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
	     positionYNow+= GAP_FONT_CHS;
	     
	   //一个条码 
		positionYNow=jumpGapOfLabel(positionYNow,BAR_HEIGHT);
		src+=getOneBar(orderJO.getLong(Order.ID)+"", positionYNow);
		src+=ENTER;	
		positionYNow+=BAR_HEIGHT;    //显示二维码数字的文本高度。
		
		//时间
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		String dateTimeAA="";
		     try {
		dateTimeAA = DateTimeFunction.transWordDateFormat(orderJO.getString(Order.DATETIMEAA));
		   } catch (Exception e) {	e.printStackTrace(); }
		src+=getOneRowWord("时间:"+dateTimeAA, PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
		positionYNow+= GAP_FONT_CHS;	
		//时间
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("地址:"+orderJO.getString(Order.MACHINENAME), PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
		positionYNow+= GAP_FONT_CHS;      
		//客户
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("客户"+orderJO.getString(Order.CUSTOMERTELNUM), PADDING_HORIZON,positionYNow,  FONT_CHS);			
		src+=ENTER;	
	    positionYNow+= GAP_FONT_CHS+5;
		 
	    JSONArray productJA= orderJO.getJSONArray("products");
		for(int i=0; i<productJA.size();i++){
			JSONObject productJO=productJA.getJSONObject(i);
			String word=spellOneProduct(productJO.getString(OrderProduct.PRODUCTNAME),productJO.getString(OrderProduct.BRANCHNAME),productJO.getString(OrderProduct.BRANCHNUM));
		//一个菜品	
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord(word, PADDING_HORIZON,positionYNow, FONT_CHS);	
		src+=ENTER;
	    positionYNow+= GAP_FONT_CHS;
	    
		//分割线		
		// src+="LS10,"+ positionYNow+","+LINE_WIDTH+",470,"+ positionYNow;
		// src+=ENTER;	
		}
		

		 positionYNow+=5; //留点空隙
	
		
		//收货人	
		positionYNow=jumpGapOfLabel(positionYNow,GAP_FONT_CHS);
		src+=getOneRowWord("商家:"+orderJO.getLong(Order.SERVICETELNUM), PADDING_HORIZON,positionYNow,  FONT_CHS);	
		src+=ENTER;		
		
		src+="P1";
		src+=ENTER;		
		return src;
	}
	
	
	private int jumpGapOfLabel(int positionY,int height){ 
		 System.out.print("position low="+(positionY));
		   System.out.print("position high="+(positionY+height)+"\n  ");
		   
		for(int i=1;i<4;i++){
			boolean isLowInGap=positionY>(i*(HEIGHT_LABEL+GAP_LABEL)-GAP_LABEL)&&positionY<i*(HEIGHT_LABEL+GAP_LABEL);
			boolean isHighInGap=(positionY+height)>(i*(HEIGHT_LABEL+GAP_LABEL)-GAP_LABEL)&&(positionY+height)<i*(HEIGHT_LABEL+GAP_LABEL);
			boolean isCrossGap=positionY<(i*(HEIGHT_LABEL+GAP_LABEL)-GAP_LABEL)&&(positionY+height)>i*(HEIGHT_LABEL+GAP_LABEL);
		//   System.out.print("gap low="+(i*(HEIGHT_LABEL+GAP_LABEL)-GAP_LABEL));
		 //  System.out.print("gap high="+(i*(HEIGHT_LABEL+GAP_LABEL))+"\n  ");	  
			if(isLowInGap||isHighInGap||isCrossGap){ //任何一种情况都必须跨过去，用新的标签页
				return i*(HEIGHT_LABEL+GAP_LABEL)+PADDING_VERTICAL;
			}
		}
		return positionY;
	}

	public void printTest(){
		
		// String src="N\r\nA50,0,0,1,1,1,N,\"Example 1\"\r\nP1\r\n";
		// String src="U\r\n";
			
		try {
			String src=getOnePrintCode();
		//	String newStr = new String(src.getBytes(), "UTF-8");
			System.out.println("ZebraPrinter.printTest()  \r\n"+src);	
		//	System.out.println("ZebraPrinter.printTest() UTF-8 \r\n"+newStr);
			serialPortOpt.writeBytes(src.getBytes("GB2312"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
	}

	public void printOrders(JSONArray orderJA ){
	
		try {
			for(int i=0;i<orderJA.size();i++){
			String src=getOneOrderCode(orderJA.getJSONObject(i));			
			System.out.println("ZebraPrinter.printTest()  \r\n"+src);	
			serialPortOpt.writeBytes(src.getBytes("GB2312"));
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
	}
	
	private void initSerialPort(){
		 
		 serialPortOpt= new SerailPortOpt();
		 serialPortOpt.mDevNum=0;
		 serialPortOpt.mDataBits=8;
		 serialPortOpt.mSpeed=9600;
		 serialPortOpt.mStopBits=1;
		 serialPortOpt.mParity='n';
		 serialPortOpt.openDev(serialPortOpt.mDevNum);
		 serialPortOpt.setSpeed(serialPortOpt.mFd, serialPortOpt.mSpeed);
		 serialPortOpt.setParity(serialPortOpt.mFd, serialPortOpt.mDataBits , serialPortOpt.mStopBits=1,  serialPortOpt.mParity);
		 mInputStream=serialPortOpt.getInputStream();
	}
	
	public void readCom(){
		new Thread(
				new Runnable() {
					
					@Override
					public void run() {
						byte[] buf= new byte[512];
						 byte[] state=null ;							   
					     long times = 0;
					     
						while(true){
							   int size;
							   times++;
							   if(times>655000) {  
							    	// break;   
							    	}
								if(mInputStream==null) { 	
								 
									continue; }				 
							     size=serialPortOpt.readBytes(buf);
							    if(size>0) {		 
							    state = new byte[size];
								System.arraycopy(buf, 0, state, 0, size);					
						       String	checkString=bytesToHexString(state,state.length);
						    	//System.out.println(" the checkRelayString is:"+checkRelayString);
						    	 System.out.println(" read from com:"+checkString);
							    }
							    }
					}
				}
				).start();
	}
	public static String bytesToHexString(byte[] src, int size) {
		String ret = "";
		if (src == null || size <= 0) {
			return null;
		}
		for (int i = 0; i < size; i++) {
			String hex = Integer.toHexString(src[i] & 0xFF);
			//Log.i(TAG, hex);
			if (hex.length() < 2) {
				hex = "0" + hex;
			}
			hex += " ";
			ret += hex;
		}
		return ret.toUpperCase();
	}
	@Override
	protected void finalize() throws Throwable {
		// TODO Auto-generated method stub
		if (serialPortOpt.mFd != null) {
		serialPortOpt.closeDev(serialPortOpt.mFd);
		System.out.println("关闭打印机用的串口");}
		
		super.finalize();
	}

}
